package main

import (
	"Bok/controllers"
	"Bok/daos"
	"Bok/database"
	_ "Bok/docs"
	"Bok/middleware"
	"Bok/services"
	"log"

	"github.com/gin-gonic/gin"
	swaggerfiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "*")
		c.Header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	}
}

// @BasePath /api
func main() {
	// 初始化数据库
	database.InitDB()

	// 创建 Gin 实例
	r := gin.Default()
	r.Use(cors())
	r.Use(middleware.JWTAuth()) // 检查 token
	// 检查 管理员权限
	// ...
	// 初始化依赖
	articleDao := daos.NewArticleDao(database.DB)
	articleService := services.NewArticleService(articleDao)
	articleController := controllers.NewArticleController(articleService)

	userDao := daos.NewUserDao(database.DB)
	userService := services.NewUserService(userDao)
	userController := controllers.NewUserController(userService)

	blogDao := daos.NewBlogDao(database.DB)
	blogService := services.NewBlogService(blogDao)
	blogController := controllers.NewBlogController(blogService)

	// 创建 API 路由依赖
	api := r.Group("/api")
	{
		// 文章相关路由
		articles := api.Group("/articles")
		{
			articles.GET("/:id", articleController.GetArticle)
			articles.POST("", articleController.CreateArticle)
			articles.DELETE("/:id", articleController.DeleteArticle)
			articles.PUT("/:id", articleController.UpdateArticle)
		}

		blogtype := api.Group("/blogtype")
		{
			blogtype.GET("", blogController.GetBlogTypeList)
			blogtype.POST("", blogController.CreateBlogType)
			blogtype.PUT("/:id", blogController.EditBlogType)
			blogtype.DELETE("/:id", blogController.DeleteBlogType)
		}
	}

	publicGroup := r.Group("/public")
	{
		publicGroup.POST("/register", userController.RegisterController) // 注册接口
		publicGroup.POST("/login", userController.LoginController)       // 登录接口
	}

	// 更改用户信息（管理员）
	user := r.Group("/user")
	{
		user.GET("/info", userController.GetUserController)
		user.PUT("/info", userController.EditUserController)
	}
	// 更信息

	// 注册Swagger路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))

	log.Println("Application started successfully!")

	// 启动服务器
	r.Run(":8080")
}
